//
//  ChatViewController.m
//  WChat
//
//  Created by lw on 2018/7/31.
//  Copyright © 2018年 mjsfax. All rights reserved.
//

#import "ChatViewController.h"
#import "ChatBottomView.h"
#import "ChatCell.h"
#import "ChatModel.h"
#import <MWPhotoBrowser.h>
#import "EMCDDeviceManager.h"
#import "AudioChatViewController.h"

@interface ChatViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, IEMChatProgressDelegate, EMChatManagerChatDelegate, UIImagePickerControllerDelegate,MWPhotoBrowserDelegate,EMCallManagerDelegate>
@property (strong, nonatomic) ChatBottomView *bottomView;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *messages;
@property (strong, nonatomic) NSMutableArray *photos;
@property (strong, nonatomic) AudioChatViewController *audioVc;
@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = self.username;
    [self.view addSubview:self.tableView];
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
    [self setupBottomView];
    [self keyboardObserve];
    [self reloadMsg];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[[EaseMob sharedInstance].chatManager conversationForChatter:self.username conversationType:eConversationTypeChat] markAllMessagesAsRead:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

#pragma mark - action

- (void)keyboardObserve {
    [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillChangeFrameNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        NSLog(@"%@",note.userInfo);
        CGFloat keyH = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
        CGFloat dur = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
        CGRect rect = self.view.frame;
        rect.origin.y = keyH-self.view.bounds.size.height;
        self.view.frame = rect;
        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
            [self.view setNeedsLayout];
            [self scrollToBottom];
        } completion:^(BOOL finished) {
            
        }];
    }];
}

- (void)setupBottomView {
    [self.view addSubview:self.bottomView];
    self.bottomView.tfInpute.delegate = self;
    self.bottomView.functionBlock = ^(KeyboardType type) {
        if (type == KeyboardTypePhoto) {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            [self presentViewController:imagePicker animated:YES completion:nil];
        } else if (type == KeyboardTypeVideo) {
            [self videoTalk];
        } else {
            NSLog(@"othertype====%d",type);
        }
    };
    self.bottomView.inputBlock = ^(MessageType type) {
        if (type == MessageTypeSpeaking) {
            NSInteger now = [[NSDate date] timeIntervalSince1970];
            NSInteger randomNum = arc4random() % 100000;
            NSString *fileName = [NSString stringWithFormat:@"%@%zd%zd",self.username, now, randomNum];
            [[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:fileName completion:^(NSError *error) {
                if (error) {
                    NSLog(@"%@",error);
                    return;
                }
                NSLog(@"正在录音");
                [MSToast show:@"正在录音"];
            }];
        } else if (type == MessageTypeSend) {
            [[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
                if (error) {
                    NSLog(@"%@",error);
                    return;
                }
                EMChatVoice *voice = [[EMChatVoice alloc] initWithFile:recordPath displayName:@"audio"];
                voice.duration = aDuration;
                EMVoiceMessageBody *body = [[EMVoiceMessageBody alloc] initWithChatObject:voice];
                EMMessage *message = [[EMMessage alloc] initWithReceiver:self.username bodies:@[body]];
                [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:self prepare:^(EMMessage *message, EMError *error) {
                    if (error) {
                        NSLog(@"%@",error);
                        return;
                    }
                    //修改显示语音信息条 一闪一闪的效果
                } onQueue:nil completion:^(EMMessage *message, EMError *error) {
                    if (error) {
                        NSLog(@"%@",error);
                        return;
                    }
                    [self reloadMsg];
                } onQueue:nil];
            }];
        } else if (type == MessageTypeCancled) {
            [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
        }
    };
}

- (void)videoTalk {
    UIAlertController *alerVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *audioChat = [UIAlertAction actionWithTitle:@"语音聊天" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        EMError *error = nil;
        EMCallSession *session = [[EaseMob sharedInstance].callManager asyncMakeVoiceCall:self.username timeout:0 error:&error];
        if (error) {
            [MSToast show:error.description];
        }
        
    }];
    UIAlertAction *videoChat = [UIAlertAction actionWithTitle:@"视频聊天" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alerVC addAction:audioChat];
    [alerVC addAction:videoChat];
    [alerVC addAction:cancel];
    [self presentViewController:alerVC animated:YES completion:nil];
    
}

#pragma mark -

- (void)reloadMsg {
    [self.messages removeAllObjects];
    [self.photos removeAllObjects];
    EMConversation *conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:self.username conversationType:eConversationTypeChat];
    //内存中会话
    //NSArray *conver = [[EaseMob sharedInstance].chatManager conversations];
    //db中会话
    //NSArray *conver = [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES];
    NSArray *mess = [conversation loadAllMessages];
    for (EMMessage *m in mess) {
        ChatModel *model = [[ChatModel alloc] init];
        model.message = m;
        if (model.chatType == ChatTypeImage) {
            [self.photos addObject:model.localThumbnailUrl];
            NSLog(@"==========%@",model.contentText);
        }
        [self.messages addObject:model];
    }
    [self.tableView reloadData];
    [self scrollToBottom];
}

- (void)scrollToBottom {
    if (self.messages.count) {
        NSIndexPath *last = [NSIndexPath indexPathForRow:self.messages.count-1 inSection:0];
        [self.tableView scrollToRowAtIndexPath:last atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}

#pragma mark - delegate  callManager

- (void)callSessionStatusChanged:(EMCallSession *)callSession changeReason:(EMCallStatusChangedReason)reason error:(EMError *)error {
//    NSLog(@"%@====%@",reason,error.description);
    //modal通话界面
    if (callSession.status == eCallSessionStatusConnected) {
        self.audioVc = [[AudioChatViewController alloc] init];
        self.audioVc.session = callSession;
        [self presentViewController:self.audioVc animated:YES completion:nil];
    } else if (callSession.status == eCallSessionStatusDisconnected) {
        if (self.audioVc) {
            __weak typeof(self)weakSelf = self;
            [self.audioVc dismissViewControllerAnimated:YES completion:^{
                weakSelf.audioVc = nil;
            }];
        }
    }
}

- (void)callSessionNetWorkStatusChanged:(EMCallSession *)callSession changeReason:(EMCallStatusNetWorkChangedReason)reason error:(EMError *)error {
    NSLog(@"%d",reason);
}

#pragma mark - delegate : SDK

- (void)setProgress:(float)progress {
    NSLog(@"%s, line = %d",__FUNCTION__, __LINE__);
}

- (void)setProgress:(float)progress forMessage:(EMMessage *)message forMessageBody:(id<IEMMessageBody>)messageBody {
    NSLog(@"%s, line = %d",__FUNCTION__, __LINE__);
}

//接受消息
- (void)didReceiveMessage:(EMMessage *)message {
    [self reloadMsg];
}
//接收离线非透传消息
- (void)didReceiveOfflineMessages:(NSArray *)offlineMessages {
    [self reloadMsg];
}

#pragma mark - send message

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *origin = info[UIImagePickerControllerOriginalImage];
    NSData *data = UIImageJPEGRepresentation(origin, 0.5);
    UIImage *img = [UIImage imageWithData:data];
    //发送图片消息
    EMChatImage *chatImage = [[EMChatImage alloc] initWithUIImage:img displayName:@"chatimage"];
    EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithChatObject:chatImage];
    EMMessage *message = [[EMMessage alloc] initWithReceiver:self.username bodies:@[body]];
    
    __weak typeof(self) weakSelf = self;
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:self prepare:^(EMMessage *message, EMError *error) {
        
        if (error) {
            NSLog(@"%@",error);
        }
        
    } onQueue:nil completion:^(EMMessage *message, EMError *error) {
        if (!error) {
            NSLog(@"发送成功");
            [weakSelf reloadMsg];
        }
    } onQueue:nil];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    //发送消息
    EMChatText *txtChat = [[EMChatText alloc] initWithText:textField.text];
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:txtChat];
    
    EMMessage *message = [[EMMessage alloc] initWithReceiver:self.username bodies:@[body]];
    message.messageType = eMessageTypeChat;
    
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:self prepare:^(EMMessage *message, EMError *error) {
        
    } onQueue:nil completion:^(EMMessage *message, EMError *error) {
        if (error) {
            [MSToast show:error.description];
            return;
        }
        textField.text = nil;
        [self reloadMsg];
        if (!self.messages.count) {
            return;
        }
        
    } onQueue:nil];
    
    return YES;
}

#pragma mark - delegate : tableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.messages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ChatCell *cell = [ChatCell cellWithTableView:tableView];
    ChatModel *message = [self.messages objectAtIndex:indexPath.row];
    cell.model = message;
    cell.actionBlock = ^(ChatType type) {
        if (type == ChatTypeImage) {
            MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
            NSInteger index = [self.photos indexOfObject:message.localThumbnailUrl];
            [browser setCurrentPhotoIndex:index];
            [self.navigationController pushViewController:browser animated:YES];
        }
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    ChatModel *m = [self.messages objectAtIndex:indexPath.row];
    return m.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - delegat : phone
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return 1;
}

- (id<MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    UIImage *image = [UIImage imageWithContentsOfFile:[self.photos objectAtIndex:index]];
    MWPhoto *photo = [MWPhoto photoWithImage:image];
    return photo;
}

- (id<MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
    UIImage *image = [UIImage imageWithContentsOfFile:[self.photos objectAtIndex:index]];
    MWPhoto *photo = [MWPhoto photoWithImage:image];
    return photo;
}
/*
//返回对应MWCaptionView
- (MWCaptionView *)photoBrowser:(MWPhotoBrowser *)photoBrowser captionViewForPhotoAtIndex:(NSUInteger)index {
    
}
//修改标题
- (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index {
}
//展示时候调用
- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index {
}
//图上某按钮点击
- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser actionButtonPressedForPhotoAtIndex:(NSUInteger)index {
}
//是否选中
- (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index {
}
//选中图片改变
- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected {
}
//结束展示
- (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser {
}
 */
#pragma mark - lazy

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, SCREENHEIGHT-64-50) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (ChatBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [ChatBottomView instance];
        _bottomView.frame = CGRectMake(0, SCREENHEIGHT-50, SCREENWIDTH, 50);
    }
    return _bottomView;
}

- (NSMutableArray *)messages {
    if (!_messages) {
        _messages = [NSMutableArray array];
    }
    return _messages;
}

- (NSMutableArray *)photos {
    if (!_photos) {
        _photos = [NSMutableArray array];
    }
    return _photos;
}

@end
